package com.example.project3.handler;

import com.example.project3.exception.ServiceException;
import com.example.project3.util.API;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName ExceptionHandler .java
 * @Description empty
 * @Author LiuJinyu
 * @Date 2023/3/16 13:50
 * @Version 1.0
 */
@RestControllerAdvice
@Slf4j
public class MyExceptionHandler {
    @RequestMapping("/error")
    public void error(HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        String errorMessage = request.getAttribute("error").toString();
        throw new ServiceException(errorMessage);
    }

    @ExceptionHandler(value = ServiceException.class)
    public API serviceException(ServiceException e) {
        return API.failed("服务错误", e.getMessage());
    }

    @ExceptionHandler(value = NullPointerException.class)
    public API nullPointerException(NullPointerException e) {
        log.warn("没有信息", e);
        return API.failed("没有信息", e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public API exception(Exception e) {
        e.printStackTrace();
        return API.failed("内部服务器错误");
    }
}
